<template>
	<view class="check-code-page">
		<!-- 顶部核销按钮 -->
		<view class="check-section">
			<view class="check-button" @click="startScan">
				<text class="check-text">点击扫码核销</text>
			</view>
		</view>

		<!-- 今日核销统计 -->
		<view class="stats-section">
			<view class="stats-card">
				<view class="stat-item">
					<text class="stat-number">{{ dailyStats.checkCount }}</text>
					<text class="stat-label">今日核销数量</text>
				</view>
				<view class="stat-divider"></view>
				<view class="stat-item">
					<text class="stat-number">¥{{ dailyStats.totalAmount }}</text>
					<text class="stat-label">今日核销金额</text>
				</view>
			</view>
		</view>

		<!-- 核销记录标题 -->
		<view class="record-title">
			<text>核销记录</text>
			<view class="title-line"></view>
		</view>

		<!-- 核销记录列表 -->
		<scroll-view
			class="record-list"
			scroll-y
			@scrolltolower="loadMore"
			refresher-enabled
			@refresherrefresh="refreshData"
			:refresher-triggered="refreshing"
			:lower-threshold="100">

			<view v-if="recordList.length === 0 && !loading" class="empty-state">
				<view class="empty-icon">📋</view>
				<text class="empty-text">暂无核销记录</text>
			</view>

			<view v-for="(item, index) in recordList" :key="index" class="record-item">
				<view class="record-header">
					<view class="project-info">
						<text class="project-name">{{ item.parent_product_name }} {{ item.product_name || '未知项目' }}</text>
						<text class="record-time">{{ formatTime(item.verify_time) }}</text>
					</view>
					<view class="status-badge" :class="[getStatusClass(item.status)]">
						{{ getStatusText(item.status) }}
					</view>
				</view>
				<view class="record-details">
					<view class="detail-item">
						<text class="label">核销码：</text>
						<text class="value">{{ item.code || '--' }}</text>
					</view>
					<view class="detail-item">
						<text class="label">订单号：</text>
						<text class="value">{{ item.order_no || '--' }}</text>
					</view>
					<view class="detail-item" v-if="item.user">
						<text class="label">用户：</text>
						<text class="value">{{ item.user.nickname }}</text>
					</view>
          <view class="detail-item" v-if="item.user">
            <text class="label">联系方式：</text>
            <text class="value">{{ item.user.phone }}</text>
          </view>
				</view>
			</view>

			<!-- 加载状态 -->
			<view v-if="loading" class="loading-state">
				<text>加载中...</text>
			</view>

			<view v-if="!hasMore && recordList.length > 0" class="no-more">
				<text>没有更多数据了</text>
			</view>

			<!-- 底部安全距离 -->
			<view class="bottom-safe"></view>
		</scroll-view>

		<!-- 核销成功弹窗 -->
		<view v-if="showSuccessModal" class="success-modal" @click="hideSuccessModal">
			<view class="modal-content" @click.stop>
				<view class="success-title">核销成功</view>
				<view class="success-info">
					<view class="info-item">
						<text class="info-label">项目名称：</text>
						<text class="info-value">{{ successInfo.productTitle }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">订单号：</text>
						<text class="info-value">{{ successInfo.orderSn }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">核销时间：</text>
						<text class="info-value">{{ successInfo.checkTime }}</text>
					</view>
				</view>
				<view class="modal-button" @click="hideSuccessModal">
					确定
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				recordList: [],
				loading: false,
				refreshing: false,
				hasMore: true,
				currentPage: 1,
				pageSize: 10,
				showSuccessModal: false,
				successInfo: {
					productTitle: '',
					orderSn: '',
					checkTime: ''
				},
				dailyStats: {
					checkCount: 0,
					totalAmount: 0
				}
			}
		},
		onLoad() {
			this.loadRecordList()
			this.loadDailyStats()
		},
		onShow() {
			// 页面显示时刷新列表
			// this.refreshData()
      // this.handleScanResult('bf472630')
		},
		methods: {
			// 开始扫码
			startScan() {
				uni.scanCode({
					success: (res) => {
						console.log('扫码结果:', res)
						this.handleScanResult(res.result)
					},
					fail: (err) => {
						console.error('扫码失败:', err)
						uni.showToast({
							title: '扫码失败，请重试',
							icon: 'none'
						})
					}
				})
			},

			// 处理扫码结果
			async handleScanResult(code) {
				if (!code) {
					uni.showToast({
						title: '扫码结果为空',
						icon: 'none'
					})
					return
				}

				uni.showLoading({
					title: '核销中...'
				})
        this.$api.checkCode({
          code: code,
          shop_user_id: this.userInfo.id,
        }).then(res => {
          this.refreshData()
          this.loadDailyStats()
          setTimeout(() => {
            uni.showToast({
              title: '核销成功',
            })
          },500)
        })
			},

			// 加载核销记录列表
			async loadRecordList(isRefresh = false) {
				if (this.loading) return

				if (isRefresh) {
					this.currentPage = 1
					this.hasMore = true
				}

				console.log('开始加载数据，页码:', this.currentPage, '是否刷新:', isRefresh)
				this.loading = true

				try {
					const res = await this.$api.getCheckCodeRecords({
						pageNo: this.currentPage,
						pageSize: this.pageSize,
						shop_user_id: this.userInfo.id,
						status: 1
					})

					const newData = res.list || []
					const total = res.total || 0
					console.log('接口返回数据:', { newData: newData.length, total, currentPage: this.currentPage })

					if (isRefresh) {
						this.recordList = newData
					} else {
						this.recordList = [...this.recordList, ...newData]
					}

					// 判断是否还有更多数据：当前返回的数据量等于请求的页面大小，且总数据量大于当前已加载的数据量
					this.hasMore = newData.length === this.pageSize && this.recordList.length < total
					console.log('加载完成，总数据量:', this.recordList.length, '是否还有更多:', this.hasMore)

					// 如果成功加载了数据，页码+1
					if (newData.length > 0) {
						this.currentPage++
					}

				} catch (error) {
					console.error('加载核销记录失败:', error)
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					})
				} finally {
					this.loading = false
					if (isRefresh) {
						this.refreshing = false
					}
				}
			},

			// 加载今日核销统计
			async loadDailyStats() {
				try {
					const today = new Date()
					const dateStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`

					const res = await this.$api.getDailyCheckStats({
						shop_user_id: this.userInfo.id,
						date: dateStr
					})

					this.dailyStats = {
						checkCount: res.checkCount || 0,
						totalAmount: res.totalAmount || 0
					}
				} catch (error) {
					console.error('获取今日统计失败:', error)
					this.dailyStats = {
						checkCount: 0,
						totalAmount: 0
					}
				}
			},

			// 下拉刷新
			refreshData() {
				this.refreshing = true
				Promise.all([
					this.loadRecordList(true),
					this.loadDailyStats()
				]).finally(() => {
					this.refreshing = false
				})
			},

			// 上拉加载更多
			loadMore() {
				console.log('触发上拉加载，hasMore:', this.hasMore, 'loading:', this.loading)
				if (this.hasMore && !this.loading) {
					console.log('开始加载更多数据，当前页:', this.currentPage)
					this.loadRecordList(false)
				}
			},

			// 隐藏成功弹窗
			hideSuccessModal() {
				this.showSuccessModal = false
			},

			// 格式化时间
			formatTime(time) {
				if (!time) return '--'
				const date = new Date(time)
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				const hours = String(date.getHours()).padStart(2, '0')
				const minutes = String(date.getMinutes()).padStart(2, '0')
				return `${year}-${month}-${day} ${hours}:${minutes}`
			},

			// 获取状态样式类
			getStatusClass(status) {
				switch (status) {
					case 1:
						return 'status-success'
					case 0:
						return 'status-failed'
					default:
						return 'status-pending'
				}
			},

			// 获取状态文本
			getStatusText(status) {
				switch (status) {
					case 1:
						return '成功'
					case 0:
						return '失败'
					default:
						return '处理中'
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
page {
  height: 100%;
  overflow: hidden;
}
.check-code-page {
	background-color: #f5f5f5;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.check-section {
	padding: 40rpx 30rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	justify-content: center;
	align-items: center;
}

.check-button {
	background-color: rgba(255, 255, 255, 0.9);
	border-radius: 20rpx;
	padding: 40rpx 60rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
	transition: all 0.3s ease;

	&:active {
		transform: scale(0.95);
		background-color: rgba(255, 255, 255, 0.8);
	}
}

.scan-icon {
	font-size: 80rpx;
	margin-bottom: 20rpx;
}

.check-text {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.stats-section {
	padding: 20rpx 30rpx;
	background-color: #f5f5f5;
}

.stats-card {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	display: flex;
	align-items: center;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.stat-item {
	flex: 1;
	text-align: center;
}

.stat-number {
	display: block;
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 8rpx;
}

.stat-label {
	font-size: 24rpx;
	color: #666;
}

.stat-divider {
	width: 2rpx;
	height: 60rpx;
	background-color: #e5e5e5;
	margin: 0 30rpx;
}

.record-title {
	padding: 30rpx;
	display: flex;
	align-items: center;

	text {
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
		margin-right: 20rpx;
	}
}

.title-line {
	flex: 1;
	height: 2rpx;
	background-color: #e5e5e5;
}

.record-list {
  flex: 1;
  width: 100%;
	padding: 0 30rpx;
  box-sizing: border-box;
  height: 0; /* 关键：配合flex使用，确保有明确高度 */
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 120rpx 0;
}

.empty-icon {
	font-size: 120rpx;
	margin-bottom: 30rpx;
	opacity: 0.5;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}

.record-item {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.record-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 20rpx;
}

.project-info {
	flex: 1;
}

.project-name {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	display: block;
	margin-bottom: 8rpx;
}

.record-time {
	font-size: 24rpx;
	color: #999;
}

.status-badge {
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	color: #fff;

	&.status-success {
		background-color: #52c41a;
	}

	&.status-failed {
		background-color: #ff4d4f;
	}

	&.status-pending {
		background-color: #faad14;
	}
}

.record-details {
	border-top: 1rpx solid #f0f0f0;
	padding-top: 20rpx;
}

.detail-item {
	display: flex;
	margin-bottom: 12rpx;

	&:last-child {
		margin-bottom: 0;
	}
}

.label {
	font-size: 26rpx;
	color: #666;
	width: 140rpx;
	flex-shrink: 0;
}

.value {
	font-size: 26rpx;
	color: #333;
	flex: 1;
}

.loading-state,
.no-more {
	text-align: center;
	padding: 30rpx;
	font-size: 26rpx;
	color: #999;
}

.bottom-safe {
	height: 60rpx;
}

.success-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 9999;
}

.modal-content {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 60rpx 40rpx 40rpx;
	margin: 0 60rpx;
	text-align: center;
	max-width: 600rpx;
	width: 100%;
}

.success-icon {
	font-size: 120rpx;
	margin-bottom: 30rpx;
}

.success-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 40rpx;
}

.success-info {
	text-align: left;
	margin-bottom: 40rpx;
}

.info-item {
	display: flex;
	margin-bottom: 20rpx;

	&:last-child {
		margin-bottom: 0;
	}
}

.info-label {
	font-size: 28rpx;
	color: #666;
	width: 160rpx;
	flex-shrink: 0;
}

.info-value {
	font-size: 28rpx;
	color: #333;
	flex: 1;
}

.modal-button {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: #fff;
	padding: 24rpx 80rpx;
	border-radius: 50rpx;
	font-size: 32rpx;
	font-weight: 600;

	&:active {
		opacity: 0.8;
	}
}
</style>
